﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;


namespace projetoFinal
{
    public class DAOHelper {

        private const string ID_CONNECTION = "MySql";        
        public  const  int EQUALS = 1;
	    public  const  int GREATHER_THAN = 2;
	    public  const  int LESS_THAN = 3;
	    public  const  int GREATHER_OR_EQUAL_THAN = 4;
	    public  const  int GREATHER_OR_LESS_THAN = 5;
	    public  const  int CONTAINS = 6;

        public static IDataReader executeQuery(string query)
        {
            try
            {
                Database db = DatabaseFactory.CreateDatabase(DAOHelper.ID_CONNECTION);
                IDataReader dr = db.ExecuteReader(CommandType.Text, query.ToString());
                return dr;                
            }
            catch (Exception ex)
            {
                throw new Exception("Conexão indisponível: " + ex.Message);
            }
        }

        public static int executeDML(string query)
        {
            try
            {
                Database db = DatabaseFactory.CreateDatabase(DAOHelper.ID_CONNECTION);
                int iRetorno = db.ExecuteNonQuery(CommandType.Text, query.ToString());
                return iRetorno;
            }
            catch (Exception ex)
            {
                throw new Exception("Conexão indisponível: " + ex.Message);
            }
        }

        public static string sqlQueryBuilder(string table, string field, string value, int crit)
        {
            string strRetorno = " select * from {0} where {1} {2} {3} ";            
            string strOperator = string.Empty;

            switch (crit)
            {
                case DAOHelper.EQUALS:
                    strOperator = "=";
                    break;
                case DAOHelper.GREATHER_THAN:
                    strOperator = ">";
                    break;
                case DAOHelper.LESS_THAN:
                    strOperator = "<";
                    break;
                case DAOHelper.GREATHER_OR_EQUAL_THAN:
                    strOperator = ">=";
                    break;
                case DAOHelper.GREATHER_OR_LESS_THAN:
                    strOperator = "<=";
                    break;
                default:
                    strOperator = "=";
                    break;
            }

            if (crit == DAOHelper.CONTAINS)
            {
                strRetorno = String.Format(strRetorno, table, field, "like", "'%" + value + "%'");
            }
            else
            {
                strRetorno = String.Format(strRetorno, table, field, strOperator, "'" + value + "'");
            }
            return strRetorno;
        }
    }
}